import { request } from './axios';
import { message } from 'ant-design-vue';

// 响应头：返回数据格式
const CONTENT_TYPE = {
    formData: { 'Content-Type': 'multipart/form-data' },
    applicationJson: { 'Content-Type': 'application/json' }
}

// ================================= 对外提供请求方法：通用请求，get， post, 下载download等 =================================

/**
 * get请求
 */
export const getRequest = (url, params, config = { inDataFlag: false, formDataFlag: false, noToken: false }) => {
    return request({ ...config, url, method: 'get', params });
};

/**
 * post请求
 */
export const postRequest = (url, data, config = { inDataFlag: true, formDataFlag: true, noToken: false }) => {
    if (config.inDataFlag) {
        return request({
            ...config,
            data: JSON.stringify(data),
            url,
            method: 'post',
            headers: config.formDataFlag ? { ...CONTENT_TYPE.formData } : { ...CONTENT_TYPE.applicationJson }
        });
    }
    return request({
        ...config,
        params: data,
        url,
        method: 'post',
        headers: config.formDataFlag ? { ...CONTENT_TYPE.formData } : { ...CONTENT_TYPE.applicationJson }
    });
};

// ================================= 加密 =================================

/**
 * 加密请求参数的post请求
 */
export const postEncryptRequest = (url, data) => {
    return request({
        data: { encryptData: encryptData(data) },
        url,
        method: 'post',
    });
};

// ================================= 下载 =================================

export const postDownload = function (url, data) {
    request({
        method: 'post',
        url,
        data,
        responseType: 'blob',
    })
        .then((data) => {
            handleDownloadData(data);
        })
        .catch((error) => {
            handleDownloadError(error);
        });
};

/**
 * 文件下载
 */
export const getDownload = function (url, params) {
    request({
        method: 'get',
        url,
        params,
        responseType: 'blob',
    })
        .then((data) => {
            handleDownloadData(data);
        })
        .catch((error) => {
            handleDownloadError(error);
        });
};

function handleDownloadError(error) {
    if (error instanceof Blob) {
        const fileReader = new FileReader();
        fileReader.readAsText(error);
        fileReader.onload = () => {
            const msg = fileReader.result;
            const jsonMsg = JSON.parse(msg);
            message.destroy();
            message.error(jsonMsg.msg);
        };
    } else {
        message.destroy();
        message.error('网络发生错误', error);
    }
}

function handleDownloadData(response) {
    if (!response) {
        return;
    }

    // 获取返回类型
    let contentType = _.isUndefined(response.headers['content-type']) ? response.headers['Content-Type'] : response.headers['content-type'];

    // 构建下载数据
    let url = window.URL.createObjectURL(new Blob([response.data], { type: contentType }));
    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;

    // 从消息头获取文件名
    let str = _.isUndefined(response.headers['content-disposition'])
        ? response.headers['Content-Disposition'].split(';')[1]
        : response.headers['content-disposition'].split(';')[1];

    let filename = _.isUndefined(str.split('fileName=')[1]) ? str.split('filename=')[1] : str.split('fileName=')[1];
    link.setAttribute('download', decodeURIComponent(filename));

    // 触发点击下载
    document.body.appendChild(link);
    link.click();

    // 下载完释放
    document.body.removeChild(link); // 下载完成移除元素
    window.URL.revokeObjectURL(url); // 释放掉blob对象
}